package com.rabbitmq.demo.controller;

import com.rabbitmq.demo.conf.WorkQueueConfig;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 工作模式生产者
 * @Author yi.cheng
 * @Date 2023-7-12 14:14
 **/
@RestController
public class WorkQueueProducer {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/api/work")
    public String sendWorkQueueMsg(){
        String msg = "this is work queue message";
        // 组装消息数据
        String msgId = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
        Map<String,Object> message= new HashMap<>();
        message.put("sendTime",sdf.format(new Date()));
        message.put("msg", msg);
        message.put("msgId",msgId);

        rabbitTemplate.convertAndSend(WorkQueueConfig.WORK_QUEUE_NAME,message,message1 -> {
            MessageProperties messageProperties = message1.getMessageProperties();
            // 默认消息持久化，设置消息不持久化
            messageProperties.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
            return message1;
        });
        return "ok";
    }
}
